<?php
/*
 * @component AlphaUserPoints
 * @copyright Copyright (C) 2008-2010 Bernard Gilly
 * @license : GNU/GPL
 * @Website : http://www.alphaplug.com
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

class AlphaUserPointsHelper 
{

	function newpoints ( $plugin_function='', $referrerid='', $keyreference='', $datareference='', $randompoints=0, $feedback=false, $force=0, $frontmessage='' ) 
	{		
		if ( $plugin_function!='' ) 
		{
			AlphaUserPointsHelper::userpoints ( $plugin_function, $referrerid, 0, $keyreference, $datareference, $randompoints, $feedback, $force, $frontmessage );
		} 
		else 
		{
			return;
		}	
	}	
	
	function userpoints ( $plugin_function , $referrerid='', $referraluserpoints=0, $keyreference='', $datareference='', $randompoints=0, $feedback=false, $force=0, $frontmessage='' ) 
	{	
		$checkReference = 0;

		if ( $plugin_function=='sysplgaup_recommend' && $referrerid!='' && $keyreference!='' && $datareference!='' )
		{
			$force = 1;		
		}		
		if ( !$referraluserpoints )
		{
			if ( !$referrerid )
			{
				$referrerid = @$_SESSION['referrerid'];
			}
		}
		if ( !$referrerid ) return;				
		
		if ( AlphaUserPointsHelper::checkExcludeUsers( $referrerid) ) return ;		
		$result = AlphaUserPointsHelper::checkRuleEnabled( $plugin_function, $force );
		
		// check reference if not exist
		if ( $keyreference!='' && $result ) $checkReference = AlphaUserPointsHelper::checkReference( $referrerid, $keyreference, $result[0]->id );		
		if ( $result && !$checkReference )
		{
			// force specific points -> overwriting rule points or if rule points is 0			
			// This points can be negative (example : single rule in backend for several products on frontend, each products with different prices...)
			if ( $randompoints ) $result[0]->points = $randompoints;
			
			// check if limit daily points
			if ( $result[0]->points >= 1 && $referraluserpoints==0 && $plugin_function!='sysplgaup_raffle' ) 
			{
				$result[0]->points = AlphaUserPointsHelper::checkMaxDailyPoints( $referrerid, $result[0]->points );
			}
			
			if ( AlphaUserPointsHelper::operationIsFeasible ( $referrerid, $result[0]->points ) )
			{   
			
				// check account
				AlphaUserPointsHelper::insertUserPoints( $referrerid, $result[0]->points, $result[0]->rule_expire, $result[0]->id, $referraluserpoints, $keyreference, $datareference, $result[0]->autoapproved, $result[0]->plugin_function, $result[0]->rule_name, $frontmessage );
				if ( $feedback==true ) return true;
			}
			else
			{
				// used for negative operation, 
				$error = JText::_('AUP_YOUDONOTHAVEENOUGHPOINTSTOPERFORMTHISOPERATION' );
				JError::raiseNotice(0, $error );
				if ( $feedback==true )
				{
					return false;
				} 
				else
				{
					return;
				}
			}
		} else return true;
		
	}

	function insertUserPoints( $referrerid, $points, $rule_expire='0000-00-00 00:00:00', $rule_id, $referraluserpoints=0, $keyreference='', $datareference='', $autoapproved='1', $rule_plugin='', $rule_name='', $frontmessage='' ) 
	{	
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );		
		$insertAllActivities = $params->get( 'insertAllActivities', 0 );
		
		if ( $insertAllActivities ) 
		{	
			if ( !$referrerid ) return;
		}	
		else 
		{		
			if ( !$referrerid || $points==0 ) return;
		}
		
		$jnow		=& JFactory::getDate();		
		$now		= $jnow->toMySQL();		
		$points = ( $referraluserpoints>=1 ) ? $referraluserpoints : $points ;
		
		if ( $rule_id=='' )     $rule_id     = AlphaUserPointsHelper::getRuleID( $rule_plugin );
		if ( $rule_plugin=='' ) $rule_plugin = AlphaUserPointsHelper::getPluginFunction( $rule_id ) ;
		if ( $rule_name==''   ) $rule_name   = AlphaUserPointsHelper::getNameRule( $rule_plugin );

		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_alphauserpoints'.DS.'tables');
		// save new points into alpha_userpointsdetails table
		$row =& JTable::getInstance('userspointsdetails');
		$row->id				= NULL;
		$row->referreid			= $referrerid;
		$row->points			= $points;
		$row->insert_date		= $now;
		$row->expire_date 		= $rule_expire;		
		$row->rule				= $rule_id;
		$row->approved			= $autoapproved;
		$row->status			= $autoapproved;
		$row->keyreference		= $keyreference;
		$row->datareference		= $datareference;
		if ( !$row->store() )
		{
			JError::raiseError(500, $row->getError());
		}	
		if ( $referrerid!='GUEST' && $autoapproved || $referraluserpoints>0 ) 
		{
			AlphaUserPointsHelper::updateUserPoints( $referrerid, $points, $now, $referraluserpoints, $autoapproved, $rule_plugin, $rule_id, $rule_name, $datareference, $frontmessage );
		}
	}

	function updateUserPoints( $referrerid, $assignpoints, $now, $referraluserpoints, $autoapproved, $rule_plugin='', $rule_id='', $rule_name='', $datareference='', $frontmessage='' ) 
	{
		$app = JFactory::getApplication();
		
		JPlugin::loadLanguage( 'com_alphauserpoints' );
		
		$user = & JFactory::getUser();	
		
		$db	   =& JFactory::getDBO();	
		
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );		
		$messageEnabled = $params->get('displayMSGfront');
		
		$query = "SELECT id FROM #__alpha_userpoints WHERE `referreid`='$referrerid'";
		$db->setQuery( $query );
		$referrerUser = $db->loadResult();
		
		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_alphauserpoints'.DS.'tables');				
		$row =& JTable::getInstance('userspoints');
			
		// update points into alpha_userpoints table
		$row->load( intval($referrerUser) );
		
		$referraluser = $row->referraluser;
		
		$newtotal = ( !$referraluserpoints ) ? ($row->points + $assignpoints) : $row->points + $referraluserpoints ;		
		$row->last_update = $now;	
		
		$checkWinner = 0;		
		
		if ( $row->max_points >=1 && ( $newtotal > $row->max_points ) )
		{
			// Max total was reached !
			$newtotal = $row->max_points;
			// HERE YOU CAN ADD MORE FUNCTIONS! example call other component etc...
			if ( AlphaUserPointsHelper::checkRuleEnabled( 'sysplgaup_winnernotification' ) )
			{
				// get email admins in rule
				$query = "SELECT `content_items` FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_winnernotification'";
				$db->setQuery( $query );
				$emailadmins = $db->loadResult();
				if ( $autoapproved || $referraluserpoints )
				{
					AlphaUserPointsHelper::sendwinnernotification ( $referrerid, $assignpoints, $newtotal, $emailadmins );
					
					// Uddeim notification integration
					if ( $params->get( 'sendMsgUddeim', 0 ) )
					{
						AlphaUserPointsHelper::sendUddeimWinnerNotification ( $referrerid, $assignpoints, $newtotal );
					}			
					
					$checkWinner = 1;
				}
			}
		}								
		$row->points = $newtotal;
		
		if ( $autoapproved )
		{
			if ( $rule_plugin=='sysplgaup_invitewithsuccess' )
			{
				$row->referrees = $row->referrees+1;		
			}
			$db->updateObject( '#__alpha_userpoints', $row, 'id' );

			if ( $messageEnabled && !$referraluserpoints )			
			{
				$realcurrentreferrerid = AlphaUserPointsHelper::getAnyUserReferreID( $user->id );
				switch ( $rule_plugin )
				{
					case 'sysplgaup_bonuspoints':	
					case 'sysplgaup_recommend':	
					case 'sysplgaup_reader2author':
					case 'sysplgaup_buypointswithpaypal':
					case 'sysplgaup_invite':		
						// No need congratulation...								
						break;					
					case 'sysplgaup_invitewithsuccess':
						// number points in message = assign points to new user
						$numpoints = AlphaUserPointsHelper::getPointsRule( 'sysplgaup_newregistered' );
						if ( $numpoints && $user->id ) $app->enqueueMessage( sprintf ( JText::_('AUP_CONGRATULATION'), $numpoints ));
						break;
					
					default:
						if ( ($referrerid == $realcurrentreferrerid) && $user->id )
						{
							if ( $assignpoints>0 ) 
							{	
								if ( $rule_plugin=='sysplgaup_happybirthday' ) $app->enqueueMessage( JText::_('AUP_HAPPYBIRTHDAY') );		
								$app->enqueueMessage( sprintf ( JText::_('AUP_CONGRATULATION'), $assignpoints ));														
							} 
							elseif ( $assignpoints<0 )
							{
								$app->enqueueMessage( sprintf ( JText::_('AUP_X_POINTS_HAS_BEEN_DEDUCTED_FROM_YOUR_ACCOUNT'), abs($assignpoints) ) );
							}
						}
				}
			}
		}
		
		if ( $rule_plugin=='sysplgaup_custom' && $datareference ) $rule_name = $datareference;
		
		// email notification
		if ( AlphaUserPointsHelper::checkRuleEnabled( 'sysplgaup_emailnotification' ) && !$checkWinner )
		{
			AlphaUserPointsHelper::sendnotification ( $referrerid, $assignpoints, $newtotal, $rule_name );
		}
		
		// Uddeim notification integration
		if ( $params->get( 'sendMsgUddeim', 0 ) && !$checkWinner )
		{
			AlphaUserPointsHelper::sendUddeimNotification ( $referrerid, $assignpoints, $newtotal, $rule_name );
		}
		
		// checking rank and medals and update if necessary
		if ( $rule_id=='' ) $rule_id = AlphaUserPointsHelper::getRuleID( $rule_plugin );
		AlphaUserPointsHelper::checkRankMedal( $referrerid, $rule_id );
		//AlphaUserPointsHelper::displayMessageSystem('Referre ID = ' . $referrerid .  ' - rule ID = ' . $rule_id);
		//AlphaUserPointsHelper::checkRankMedal( $referrerid );
		
		// referral points rule
		if ( $referraluserpoints==0 && $referraluser!='' && $rule_plugin!='sysplgaup_buypointswithpaypal' && $rule_plugin!='sysplgaup_raffle' && $assignpoints>0 )
		{ // if not already assign
			$query = "SELECT * FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_referralpoints' AND `published`='1' AND (`rule_expire`>'$now' OR `rule_expire`='0000-00-00 00:00:00')";
			$db->setQuery( $query );
			$referralpoints = $db->loadObjectList();		
			if ( $referralpoints )
			{
				$referraluserpoints = round(($assignpoints*$referralpoints[0]->points)/100) ;
				if ( $referraluserpoints>=1 ) AlphaUserPointsHelper::userpoints( 'sysplgaup_referralpoints', $referraluser, $referraluserpoints );	
			}
		}
		
		if ( $frontmessage!='' ) AlphaUserPointsHelper::displayMessageSystem($frontmessage);
	}
	
	function getPointsRule( $plugin_function )
	{
		$db	   =& JFactory::getDBO();
		$query = "SELECT `points` FROM #__alpha_userpoints_rules WHERE `plugin_function`='$plugin_function'";
		$db->setQuery( $query );
		$numpoints = $db->loadResult();
		return	$numpoints;	
	}
	
	function getNameRule( $plugin_function )
	{
		$db	   =& JFactory::getDBO();
		$query = "SELECT `rule_name` FROM #__alpha_userpoints_rules WHERE `plugin_function`='$plugin_function'";
		$db->setQuery( $query );
		$rule_name = $db->loadResult();
		return	$rule_name;	
	}
	
	function getRuleID( $plugin_function )
	{
		$db	   =& JFactory::getDBO();
		$query = "SELECT `id` FROM #__alpha_userpoints_rules WHERE `plugin_function`='$plugin_function'";
		$db->setQuery( $query );
		$rule_id = $db->loadResult();
		return intval($rule_id);	
	}
	
	function getPluginFunction( $id_rule )
	{
		$db	   =& JFactory::getDBO();
		$query = "SELECT `plugin_function` FROM #__alpha_userpoints_rules WHERE `id`='$id_rule'";
		$db->setQuery( $query );
		$plugin_function = $db->loadResult();
		return	$plugin_function;	
	}
	
	function getDatareference( $idActivity )
	{
		if ( $idActivity ) return;		
		$db	   =& JFactory::getDBO();
		$query = "SELECT `datareference` FROM #__alpha_userpoints_details WHERE `id`='$idActivity'";
		$db->setQuery( $query );
		$datareference = $db->loadResult();
		return	$datareference;	
	}
	
	function reader2author ( $authorid=0, $author='', $articleid=0, $title='', $url='' )
	{	
		if ( !$authorid || !$articleid ) return;		
		if ( AlphaUserPointsHelper::checkExcludeUsers( $authorid ) ) return ;	
		
		$ip = getenv('REMOTE_ADDR');				
		$db	        =& JFactory::getDBO();
		
		// check if not already view by active user
		//$query = "SELECT `id` FROM #__alpha_userpoints_details WHERE `keyreference`='$articleid' AND `datareference`LIKE '".$ip."%'";
		$query = "SELECT `id` FROM #__alpha_userpoints_details WHERE `keyreference`='" . $articleid . ":reader2author:" . $ip . "'";
		$db->setQuery( $query );
		$alreadyView = $db->loadResult();
		if ( !$alreadyView )
		{	
			$user = & JFactory::getUser();			
			$jnow		=& JFactory::getDate();
			$now		= $jnow->toMySQL();					
			$query = "SELECT * FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_reader2author' AND `published`='1' AND `access`<='" . (int) $user->aid . "' AND (`rule_expire`>'$now' OR `rule_expire`='0000-00-00 00:00:00')";
			$db->setQuery( $query );
			$result  = $db->loadObjectList();			
			if ( $result )
			{
				// get referrerid of author
				$referrerUserAuthor = AlphaUserPointsHelper::getAnyUserReferreID( $authorid );
				if ($referrerUserAuthor)
				{
					$keyreference = $articleid . ":reader2author:" . $ip;
					$datareference = '<a href="' . $url . '">' . $title . '</a> ('.$author.')' ;
					AlphaUserPointsHelper::insertUserPoints( $referrerUserAuthor, $result[0]->points, $result[0]->rule_expire, $result[0]->id, 0, $keyreference, $datareference, $result[0]->autoapproved, $result[0]->plugin_function, $result[0]->rule_name );					
				}
			}
		}
	}
	
	function checkExcludeUsers($referreID)
	{	
		$db	   =& JFactory::getDBO();			
		$excludeuser = array();		
		$query = "SELECT exclude_items FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_excludeusers' AND `published`='1'";
		$db->setQuery( $query );
		$result  = $db->loadResult();		
		if ( $result )
		{		
			$excludeuser = explode( ",", $result);
			if ( in_array( $referreID, $excludeuser ) )
			{
				return true;
			}
		}
		return false;
	}
	
	function checkRuleEnabled( $plugin_function='', $force=0 )
	{	
		if ( !$plugin_function ) return false;	
		$user = & JFactory::getUser();	
		$jnow		=& JFactory::getDate();
		$now		= $jnow->toMySQL();
		$accessrule = "";			
		switch ( $plugin_function )
		{		
			case 'sysplgaup_referralpoints': // assign to all referral users level	
			case 'sysplgaup_excludeusers':   // enabled this rule for all users level
			case 'sysplgaup_emailnotification':
			case 'sysplgaup_winnernotification':
			case 'sysplgaup_newregistered':
			case 'sysplgaup_invitewithsuccess':			
				$accessrule = "";				
				break;
			default:
				$accessrule = "AND `access`<='" . (int) $user->aid . "'";
				break;		
		}		
		if ( $force )
		{
			$accessrule = "";	
		} 
		$db	   =& JFactory::getDBO();		
		$query = "SELECT * FROM #__alpha_userpoints_rules WHERE `plugin_function`='$plugin_function' AND `published`='1' $accessrule AND (`rule_expire`>'$now' OR `rule_expire`='0000-00-00 00:00:00')";
		$db->setQuery( $query );
		$result  = $db->loadObjectList();
		return $result;	
	}
	
	function checkReference( $referrerid, $keyreference, $ruleid )
	{	
		$db	   =& JFactory::getDBO();		
		$query = "SELECT count(*) FROM #__alpha_userpoints_details WHERE `referreid`='$referrerid' AND `keyreference`='$keyreference' AND `rule`='$ruleid'";
		$db->setQuery( $query );
		$resultKeyReference = $db->loadResult();
		return $resultKeyReference;	
	}
	
	function getReferreid( $userID )
	{	
		if ( !$userID ) return;	
		// get referre ID on login	
		$db	   =& JFactory::getDBO();
		$query = "SELECT referreid FROM #__alpha_userpoints WHERE `userid`='$userID'";
		$db->setQuery( $query );
		$referreid = $db->loadResult();
		if ( $referreid )
		{		
			@session_start('alphauserpoints');	
			$_SESSION['referrerid'] = $referreid;
		}	
	}
	
	function getAnyUserReferreID( $userID )
	{	
		// get referre ID for an author etc...
		$db	   =& JFactory::getDBO();
		$query = "SELECT referreid FROM #__alpha_userpoints WHERE `userid`='".intval($userID)."'";
		$db->setQuery( $query );
		$referreid = $db->loadResult();		
		return  $referreid;		
	}
	
	function getUserInfo ( $referrerid='', $userid='' )
	{	
		if ( !$referrerid && !$userid ) return;
		
		$db	   =& JFactory::getDBO();
		
		if ( $referrerid ) {
			$where = "a.referreid='$referrerid'";		
		} elseif ( $userid ){		
			$where = "a.userid='$userid'";
		}		
		
		$query = "SELECT a.userid, a.referreid, a.upnid, a.points, a.max_points, a.last_update, " .
				 "a.referraluser, a.referrees, a.blocked, a.birthdate, a.avatar, a.levelrank, a.leveldate, " .
				 "a.gender, a.aboutme, a.website, a.phonehome, a.phonemobile, a.address, a.zipcode, a.city, a.country, " .
				 "a.education, a.graduationyear, a.job, a.facebook, a.twitter, a.icq, a.aim, a.yim, a.msn, a.skype, a.gtalk, a.xfire, a.profileviews," .
				 "a.id AS rid, u.* " .
				 "FROM #__alpha_userpoints AS a, #__users AS u " .
				 //"WHERE a.referreid='$referrerid' AND a.userid=u.id";
				 "WHERE $where AND a.userid=u.id";
		$db->setQuery( $query );
		$userinfo = $db->loadObjectList();
		return @$userinfo[0];
	}	
	
	function sendnotification ( $referrerid, $assignpoints, $newtotal, $rule_name )
	{
		$app = JFactory::getApplication();
		
		if ( !$referrerid || $referrerid=='GUEST') return;		
		
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );		
		
		$MailFrom	= $app->getCfg('mailfrom'); 	
		$FromName	= $app->getCfg('fromname'); 
		$SiteName	= $app->getCfg('sitename');			
		$userinfo   = AlphaUserPointsHelper::getUserInfo( $referrerid );		
		$email	    = $userinfo->email;
			
		if ( !$userinfo->block )
		{		
			if ( $assignpoints>0 ) 
			{
				$subject = JText::_('AUP_EMAILNOTIFICATION_SUBJECT');
				$message = sprintf ( JText::_('AUP_EMAILNOTIFICATION_MSG'), $SiteName, $assignpoints, $newtotal, JText::_($rule_name) );	
			}
			 elseif ( $assignpoints<0 )
			{
				$subject = JText::_('AUP_EMAILNOTIFICATION_SUBJECT_ACCOUNT_UPDATED');
				$message = sprintf ( JText::_('AUP_EMAILNOTIFICATION_MSG_REMOVE_POINTS'), $SiteName, abs($assignpoints), $newtotal, JText::_($rule_name) );
			}
			JUtility::sendMail( $MailFrom, $FromName, $email, $subject, $message );
		}		
	}
	
	function sendUddeimNotification ( $referrerid, $assignpoints, $newtotal, $rule_name )
	{
		$app = JFactory::getApplication();
		
		// integration Uddeim
		
		if ( !$referrerid || $referrerid=='GUEST') return;
		
		// check if component installed
		$uddeim_exist = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_uddeim'.DS.'admin.uddeimlib15.php';
		if ( !file_exists ($uddeim_exist) ) return;
		
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );		
		
		$SiteName	= $app->getCfg('sitename');			
		$userinfo   = AlphaUserPointsHelper::getUserInfo( $referrerid );		
		$fromIdUddeim = intval($params->get('fromIdUddeim'));
			
		if ( !$userinfo->block && $fromIdUddeim>0 )
		{
			//require_once (JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helpers'.DS.'uddeim.api.php');
			require_once( JPATH_SITE .DS . "components" . DS . "com_uddeim" . DS . "uddeim.api.php" );
			
			if ( $assignpoints>0 ) 
			{
				$message = sprintf ( JText::_('AUP_EMAILNOTIFICATION_MSG'), $SiteName, $assignpoints, $newtotal, JText::_($rule_name) );	
			}
			 elseif ( $assignpoints<0 )
			{
				$message = sprintf ( JText::_('AUP_EMAILNOTIFICATION_MSG_REMOVE_POINTS'), $SiteName, abs($assignpoints), $newtotal, JText::_($rule_name) );
			}
			$uddeimapi = new uddeIMAPI();
			$uddeimapi->sendNewMessage( $fromIdUddeim, $userinfo->userid , $message );
		}		
	}
	
	function sendUddeimWinnerNotification ( $referrerid, $assignpoints, $newtotal )
	{
		$app = JFactory::getApplication();
		
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );		
		
		if ( !$referrerid || $referrerid=='GUEST') return;
		
		// check if component installed
		$uddeim_exist = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_uddeim'.DS.'admin.uddeimlib15.php';
		if ( !file_exists ($uddeim_exist) ) return;
			
		$FromName	= $app->getCfg('fromname');		
		$userinfo 	= AlphaUserPointsHelper::getUserInfo( $referrerid );
		$name 		= $userinfo->name;
		$fromIdUddeim = intval($params->get('fromIdUddeim'));

		if ( !$userinfo->block && $fromIdUddeim>0 )
		{	
			//require_once (JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helpers'.DS.'uddeim.api.php');
			require_once( JPATH_SITE .DS . "components" . DS . "com_uddeim" . DS . "uddeim.api.php" );
				
			// send notification to winner
			$message = sprintf ( JText::_('AUP_EMAILWINNERNOTIFICATION_MSG_USER'), $name, $newtotal );		
			$uddeimapi = new uddeIMAPI();
			$uddeimapi->sendNewMessage( $fromIdUddeim, $userinfo->userid , $message );
		}
	
	}

	
	function sendwinnernotification ( $referrerid, $assignpoints, $newtotal, $emailadmins='' )
	{
		$app = JFactory::getApplication();
		
		if ( !$referrerid || $referrerid=='GUEST') return;		
		$MailFrom	= $app->getCfg('mailfrom'); 	
		$FromName	= $app->getCfg('fromname');		
		$userinfo 	= AlphaUserPointsHelper::getUserInfo( $referrerid );
		$name 		= $userinfo->name;
		$email	 	= $userinfo->email;
		if ( !$userinfo->block )
		{				
			// send notification to winner
			$subject = JText::_('AUP_EMAILWINNERNOTIFICATION_SUBJECT_MSG_USER');
			$message = sprintf ( JText::_('AUP_EMAILWINNERNOTIFICATION_MSG_USER'), $name, $newtotal );			
			JUtility::sendMail( $MailFrom, $FromName, $email, $subject, $message );			
			// send notification to administrators...		
			if ( $emailadmins )
			{
				$subject = JText::_('AUP_EMAILWINNERNOTIFICATION_SUBJECT_MSG_ADMIN');
				$message = sprintf ( JText::_('AUP_EMAILWINNERNOTIFICATION_MSG_ADMIN'), $name, $newtotal );				
				JUtility::sendMail( $MailFrom, $FromName, $emailadmins, $subject, $message );
			}
		}
	
	}

	function getCurrentTotalPoints ( $referreid='' )
	{	
		if ( !$referreid ) return;	
		$db	   =& JFactory::getDBO();
		$query = "SELECT points FROM #__alpha_userpoints WHERE `referreid`='".$referreid."' AND `blocked`='0'";
		$db->setQuery( $query );
		$currenttotalpoints = $db->loadResult();
		return $currenttotalpoints;		
	}
	
	function operationIsFeasible ( $referreid='', $numpoints )
	{
		if ( !$referreid ) return;
		$currentpoints = AlphaUserPointsHelper::getCurrentTotalPoints ( $referreid );
		$newtotal = $currentpoints + $numpoints;
		if ( $newtotal >=0 ) 
		{
			return true;
		}
		else
		{
			return false;
		}	
	}
	
	function checkMaxDailyPoints( $referreid='', $numpoints, $plugin_function='' )
	{	
		if ( !$referreid ) return;
		
		// get params definitions
		$params =& JComponentHelper::getParams( 'com_alphauserpoints' );
		
		// except for raffles, coupons code, bonus points, custom rule, profile etc...
		switch ( $plugin_function ) {
			case 'sysplgaup_raffle':
			case 'sysplgaup_couponpointscodes':
			case 'sysplgaup_buypointswithpaypal':
			case 'sysplgaup_bonuspoints':
			case 'sysplgaup_custom':
			case 'sysplgaup_happybirthday':
			case 'sysplgaup_profilecomplete':
			case 'sysplgaup_uploadavatar':
				return $numpoints;
				break;			
			default:
				$maxdailypoints = $params->get('limit_daily_points');		
		}
		
		if ( $maxdailypoints )
		{
			//$dateofday = JFactory::getDate()->toFormat('%Y-%m-%d'); // only compatible with PHP 5
			$dateofday = date("Y-m-d"); 
			
			$db	   =& JFactory::getDBO();
				
			// Except Raffle rule...
			$query = "SELECT id FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_raffle'";
			$db->setQuery( $query );
			$idraffle = $db->loadResult();
			
			// select only positive points earned per day
			$query = "SELECT SUM(points) FROM #__alpha_userpoints_details WHERE `referreid`='".$referreid."' AND `points` >= '1' AND `insert_date` LIKE '".$dateofday."%' AND `rule`!='".$idraffle."'";
			$db->setQuery( $query );
			$totaldailypoints = $db->loadResult();
			
			$sptotal = $totaldailypoints + $numpoints;
			
			if ( $sptotal > $maxdailypoints ) 
			{
				$sbtotal = $sptotal - $maxdailypoints;
				$numpoints = $numpoints - $sbtotal;
			}
			if ($numpoints<0) $numpoints=0;
		}		
		
		return $numpoints;
	
	}
	
	function getUserRank ( $referrerid='', $userid=0 )
	{	
		if ( !$referrerid && !$userid ) return;	
		$db	   =& JFactory::getDBO();		
		$query = "SELECT lv.*, aup.leveldate FROM #__alpha_userpoints_levelrank AS lv, #__alpha_userpoints AS aup WHERE lv.id=aup.levelrank AND (aup.referreid='".$referrerid."' OR aup.userid='".$userid."')";
		$db->setQuery( $query );
		$userrankinfo = $db->loadObjectList();
		return @$userrankinfo[0];
		
		// detail/explain
		// return $userrankinfo->id
		// return $userrankinfo->rank (name of rank)
		// return $userrankinfo->description (description of rank)		
		// return $userrankinfo->levelpoints (level points to reach this rank)
		// return $userrankinfo->typerank (return 0)
		// return $userrankinfo->icon (name file icon)
		// return $userrankinfo->image (name file image)
	}
	
	function getUserMedals ( $referrerid='', $userid=0 )
	{	
		if ( !$referrerid && !$userid ) return;	
		$db	   =& JFactory::getDBO();
		$medals = "SELECT m.id, m.medaldate, m.reason, lv.rank, lv.description, lv.icon, lv.image "
				. "\nFROM #__alpha_userpoints_medals AS m, #__alpha_userpoints_levelrank AS lv, #__alpha_userpoints AS aup "
				. "\nWHERE m.medal=lv.id AND aup.id=m.rid AND (aup.referreid='".$referrerid."' OR aup.userid='".$userid."') "
				. "\nORDER BY m.medaldate DESC";
		$db->setQuery( $medals );
		$medalslistuser = $db->loadObjectList();
		
		return @$medalslistuser;
		
		// detail/explain
		// sample -> for each ( $medalslistuser as medallistuser ) {
		// return $medallistuser->id
		// return $medallistuser->rank (name of medal)
		// return $medallistuser->description (reason for awarded)		
		// return $medallistuser->icon (name file icon)
		// return $medallistuser->image (name file image)
	}
	
	function checkRankMedal( $referrerid='', $rule_id=0 ) 
	{		
		$db	   =& JFactory::getDBO();
		
		$jnow		=& JFactory::getDate();
		$nowdate	= $jnow->toMySQL();		
		
		$query = "SELECT COUNT(*) FROM #__alpha_userpoints_levelrank WHERE `levelpoints`>'0'";
		$db->setQuery( $query );
		$rankmedalexist = $db->loadResult();
		
		// check level/rank/ medals by level points
		if ( !$rankmedalexist || !$referrerid ) return;
		
		$userinfo = AlphaUserPointsHelper::getUserInfo ( $referrerid );
		// $userinfo->rid = id of table #__alpha_userpoints
		$rid = $userinfo->rid;

		$now = $jnow->toFormat('%Y-%m-%d');
		
		// check if current rule is assigned to a rank or medal
		$currentpoints = $userinfo->points;
		
		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_alphauserpoints'.DS.'tables');				
		$row =& JTable::getInstance('userspoints');

		// check level/rank
		$query = "SELECT * FROM #__alpha_userpoints_levelrank " .
		         "WHERE `levelpoints`>0 AND `typerank`='0' ORDER BY `levelpoints` ASC";
		$db->setQuery( $query );
		$ranks = $db->loadObjectList();
		
		$previousrank = 0;
		
		for ($i=0, $n=count( $ranks ); $i < $n; $i++)
		{
			$rank 	= $ranks[$i];
			
			if ( $rank->ruleid>0 && $rank->ruleid==$rule_id ) {
				// recalculate actual total points for this rule
				$query = "SELECT SUM(points) FROM #__alpha_userpoints_details " .
						 "WHERE rule='$rule_id' AND approved='1' AND referreid='$referrerid' AND (`expire_date`>'$nowdate' OR `expire_date`='0000-00-00 00:00:00')";
				$db->setQuery( $query );
				$currentpoints = $db->loadResult();
			} else $currentpoints = $userinfo->points;
			
			if ( $currentpoints < $rank->levelpoints )
			{
				// update user rank into alpha_userpoints table
				$row->load( $rid );
				$row->levelrank = $previousrank;
				$row->leveldate = $now;				
				$db->updateObject( '#__alpha_userpoints', $row, 'id' );
				break;
			}
			 else
			{
				// update user rank into alpha_userpoints table
				$row->load( $rid );
				$row->levelrank = $rank->id;
				$row->leveldate = $now;				
				$db->updateObject( '#__alpha_userpoints', $row, 'id' );	
			}			
			
			$previousrank = $rank->id;			
		}
	
		// check medal(s)
		$query = "SELECT * FROM #__alpha_userpoints_levelrank " .
				 "WHERE `levelpoints`>0 AND `typerank`='1' ORDER BY `levelpoints` DESC";
		$db->setQuery( $query );
		$medals = $db->loadObjectList();

		for ($i=0, $n=count( $medals ); $i < $n; $i++)
		{
			$medal = $medals[$i];
			
			if ( $medal->ruleid>0 ) {
				// recalculate
				$query = "SELECT SUM(points) FROM #__alpha_userpoints_details " .
						 "WHERE rule='".$medal->ruleid."' AND approved='1' AND referreid='$referrerid' AND (`expire_date`>'$nowdate' OR `expire_date`='0000-00-00 00:00:00')";
				$db->setQuery( $query );
				$currentpoints = $db->loadResult();
			} else $currentpoints = $userinfo->points;
		
			if ( $medal->levelpoints <= $currentpoints )
			{			
				// check if user medal not already awarded
				$query = "SELECT COUNT(*) FROM #__alpha_userpoints_medals WHERE `rid`='".$rid."' AND `medal`='".$medal->id."'";
				$db->setQuery( $query );
				$alreadyexist = $db->loadResult();
				if ( !$alreadyexist ) 
				{
					// add medal
					$query = "INSERT INTO #__alpha_userpoints_medals (`id`, `rid`, `medal`, `medaldate`, `reason`) "
							. "VALUES ( '', '".$rid."', '".$medal->id."', '".$now."', '".$medal->description."');";
					$db->setQuery( $query );
					$db->query();
					break;
				}
			}
			elseif ( $medal->levelpoints > $currentpoints ) 
			{			
				// check if user medal not already awarded
				$query = "SELECT COUNT(*) FROM #__alpha_userpoints_medals WHERE `rid`='".$rid."' AND `medal`='".$medal->id."'";
				$db->setQuery( $query );
				$allreadyexist = $db->loadResult();
				if ( $allreadyexist ) //if he has, we delete it as he should not have it
				{
					// delete medal					
					$query = "DELETE FROM #__alpha_userpoints_medals WHERE `rid`='".$rid."' AND  `medal`='".$medal->id."'";
					$db->setQuery( $query );
					$db->query();
					break;
				}
			}			
			
		}			
	
	}
	
	function getAupLinkToProfil( $userid, $Itemid='', $xhtml=true )
	{
		if ( !$userid ) return;
		
		($Itemid!='') ? $theItemid = "&amp;Itemid=".$Itemid : $theItemid = AlphaUserPointsHelper::getItemidAupProfil();
		
		$profile 	  = AlphaUserPointsHelper::getUserInfo('', $userid);
		$linktoprofil = "index.php?option=com_alphauserpoints&amp;view=account&amp;userid=" . $profile->referreid . $theItemid;
		$linktoprofil = JRoute::_($linktoprofil, $xhtml);
		return $linktoprofil;
		
		// USAGE
		// $linktoAUPprofil = AlphaUserPointsHelper::getAupLinkToProfil($userid);   OR  $linktoAUPprofil = AlphaUserPointsHelper::getAupLinkToProfil($userid, $YourItemid); 
		// Think to call and include this API helper.php in your script
	}
	
	function getAupUsersURL($xhtml = true)
	{
		$db	   =& JFactory::getDBO();
		$ItemidListUsers = "";
		
		$query = "SELECT id FROM #__menu WHERE `link`='index.php?option=com_alphauserpoints&view=users' AND `type`='component' AND `published`='1'";
		$db->setQuery( $query );
		$AupItemidUsers = $db->loadResult();
		
		if ( $AupItemidUsers ) $ItemidListUsers = "&amp;Itemid=" . $AupItemidUsers;
					
		$linktousers = "index.php?option=com_alphauserpoints&amp;view=users" . $ItemidListUsers;
		$linktousers = JRoute::_($linktousers, $xhtml);
			
		return $linktousers;
		
		// USAGE
		// $linktoListUsers = AlphaUserPointsHelper::getAupUsersURL();
		// IMPORTANT : A menu must be first created to List Users from the component AlphaUserPoints (using params of this menu)	
		// Think to call and include this API helper.php in your script
	}
	
	function getAvatarPath( $userid )
	{
		if(!defined("_AUP_AVATAR_PATH")) {
			define('_AUP_AVATAR_PATH', JURI::root() . 'components'.DS.'com_alphauserpoints'.DS.'assets'.DS.'images'.DS.'avatars'.DS);
		}
		$profile 	 = AlphaUserPointsHelper::getUserInfo('', $userid);
		//$avatarPath  = ( $profile->avatar!='' ) ? _AUP_AVATAR_PATH . $profile->avatar : _AUP_AVATAR_PATH . 'generic_gravatar_grey.gif' ;
		$avatarPath  = ( $profile->avatar!='' ) ? _AUP_AVATAR_PATH . $profile->avatar : _AUP_AVATAR_PATH . 'generic_gravatar_grey.png' ;

		return avatarPath ;
	}
	
	function getAvatarLivePath( $userid )
	{
		if(!defined("_AUP_AVATAR_LIVE_PATH")) {
			define('_AUP_AVATAR_LIVE_PATH', JURI::base(true) . '/components/com_alphauserpoints/assets/images/avatars/');
		}		
		//$avatarLivePath  = ( $profile->avatar!='' ) ? _AUP_AVATAR_LIVE_PATH . $profile->avatar : _AUP_AVATAR_LIVE_PATH . 'generic_gravatar_grey.gif' ;
		$avatarLivePath  = ( $profile->avatar!='' ) ? _AUP_AVATAR_LIVE_PATH . $profile->avatar : _AUP_AVATAR_LIVE_PATH . 'generic_gravatar_grey.png' ;
		return $avatarLivePath;
	}
	
	function getAupAvatar( $userid, $linktoprofil=0, $width=48, $height=48, $class='', $otherprofileurl='' )
	{
		if ( !$userid ) return;
		if(!defined("_AUP_AVATAR_PATH")) {
			// prevent call in administrator backend 
			$juriroot = str_replace( DS .'administrator', '', JURI::root());
			//define('_AUP_AVATAR_PATH', JURI::root() . 'components'.DS.'com_alphauserpoints'.DS.'assets'.DS.'images'.DS.'avatars'.DS);
			define('_AUP_AVATAR_PATH', JURI::root() . 'components'.DS.'com_alphauserpoints'.DS.'assets'.DS.'images'.DS.'avatars'.DS);
		} else $juriroot = $juriroot = str_replace( DS .'administrator', '', JURI::root());
		
		if(!defined("_AUP_AVATAR_LIVE_PATH")) {
			// prevent call in administrator backend 
			$juribase = str_replace('/administrator', '', JURI::base());
			//define('_AUP_AVATAR_LIVE_PATH', JURI::base(true) . '/components/com_alphauserpoints/assets/images/avatars/');
			define('_AUP_AVATAR_LIVE_PATH', $juribase . 'components/com_alphauserpoints/assets/images/avatars/');
		} else $juribase = str_replace('/administrator', '', JURI::base());
		
		$startprofil = "";
		$endprofil = "";
		$setwidth  = ( $width !='' ) ? ' width="'.$width.'"'   : '';
		$setheight = ( $height!='' ) ? ' height="'.$height.'"' : '';
		
		$setclass  = ( $class!='' )  ? ' class="'.$class.'"'   : '';
		
		$profile  = AlphaUserPointsHelper::getUserInfo('', $userid);
				
		//$avatar 			= ( $profile->avatar!='' ) ? _AUP_AVATAR_LIVE_PATH . $profile->avatar : _AUP_AVATAR_PATH . 'generic_gravatar_grey.gif' ;
		$avatar 			= ( $profile->avatar!='' ) ? _AUP_AVATAR_LIVE_PATH . $profile->avatar : _AUP_AVATAR_PATH . 'generic_gravatar_grey.png' ;
		
		//$avatar 			= JURI::root() . "components/com_alphauserpoints/assets/phpThumb/phpThumb.php?src=".$avatar."&amp;w=" . $width ."&amp;h=" . $height;
		$avatar 			= $juriroot . "components/com_alphauserpoints/assets/phpThumb/phpThumb.php?src=".$avatar."&amp;w=" . $width ."&amp;h=" . $height;
		
		
		$avatar				= '<img src="' . $avatar . '" border="0" alt=""' . $setwidth . $setheight . $setclass . ' />';
		$profileitemid		= '';
		if ( $linktoprofil ) {
			$profileitemid  = '&amp;Itemid=' . AlphaUserPointsHelper::getItemidAupProfil();	
			$profil = "index.php?option=com_alphauserpoints&amp;view=account&amp;userid=".$profile->referreid.$profileitemid;
			if ($otherprofileurl) $profil = $otherprofileurl;
			$startprofil	= "<a href=\"" . JRoute::_($profil) . "\">";
			$endprofil   	= "</a>";
			$avatar		 	= $startprofil . $avatar . $endprofil;
		}		
		return $avatar;
		
		// USAGE
		// $avatar = AlphaUserPointsHelper::getAupAvatar($userid, [int $linktoprofil], [int $width], [int $height], [string $class], [string $otherprofileurl]);
		// if $linktoprofil set to 1, display avatar with the link to the AUP profil of this user
		// Think to call and include this API helper.php in your script
	}
	
	function getItemidAupProfil()
	{
		$db	   =& JFactory::getDBO();
		
		$query = "SELECT id FROM #__menu WHERE `link`='index.php?option=com_alphauserpoints&view=account' AND `type`='component' AND `published`='1'";
		$db->setQuery( $query );
		$AupItemidProfile = $db->loadResult();
			
		return $AupItemidProfile;
	
	}
	
	function displayMessageSystem($message) 
	{
		$app = JFactory::getApplication();
		$app->enqueueMessage( $message );
		return true;
	}
	
	function getAupVersion()
	{
		require_once ( JPATH_ROOT . DS . 'administrator' . DS . 'components' . DS . 'com_alphauserpoints' . DS . 'assets' . DS . 'includes' . DS . 'version.php' );
		return _ALPHAUSERPOINTS_NUM_VERSION;
	}
	
}
?>